package com.eatme.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

@Configuration
public class CorsConfig {

   @Bean
   public CorsFilter corsFilter() {
      CorsConfiguration corsConfiguration = new CorsConfiguration();
      //1,允许任何来源 *表示任何请求都视为同源(生产环境尽量在配置文件中动态配置部署到的域名)，若需指定ip和端口可以改为如“localhost：8080”
      corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
      //2,允许任何请求头
      corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
      //3,允许任何方法
      corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
      //4,允许凭证
      corsConfiguration.setAllowCredentials(true);

//      corsConfiguration.addAllowedOrigin("*");
//      corsConfiguration.addAllowedOriginPattern("*");

      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", corsConfiguration);
      return new CorsFilter(source);
   }

}
